import { request } from 'umi';

/**
 * 获取所有输入源
 */
export const getApiSummary = (server: string) => {
  return request<any>(`${server}/api/summary?json=1`, {
    getResponse: true,
  });
};

/**
 * 获取rtmp推流列表
 * @param server
 */
export const getRtmpList = (
  server: string,
): Promise<{ data: { Path: string }[] }> => {
  return request<any>(`${server}/rtmp/api/list`, {
    getResponse: true,
  });
};

/**
 * 从远程服务器拉流到本地服务器
 * @param server
 * @param rtmpStreamUrl
 * @param streamPath
 */
export const pullRtmp = async (
  server: string,
  rtmpStreamUrl: string,
  streamPath: string,
) => {
  const { data } = await getRtmpList(server);
  if ((data || []).filter((d) => d.Path === streamPath).length > 0) {
    return;
  }
  return await request<any>(
    `${server}/rtmp/api/pull?target=${rtmpStreamUrl}&streamPath=${streamPath}`,
    {
      getResponse: true,
    },
  );
};

export const startM7sRecord = (
  server: string,
  type: 'flv' | 'mp4' | 'hls' | 'raw',
  streamPath: string,
): Promise<{ data: string | 'recorder exist'; status: 200 | 500 }> => {
  return request<any>(
    `${server}/record/api/start?type=${type}&streamPath=${streamPath}`,
    {
      getResponse: true,
    },
  ) as any;
};

export const stopM7sRecord = (
  server: string,
  id: string,
): Promise<{ data: 'ok' | 'no such recorder'; status: 200 | 400 | 500 }> => {
  return request<any>(`${server}/record/api/stop?id=${id}`, {
    getResponse: true,
  }) as any;
};

export const listM7sRecording = (
  server: string,
): Promise<{ data: 'null' | { ID: string }[]; status: 200 | 400 | 500 }> => {
  return request<any>(`${server}/record/api/list/recording`, {
    getResponse: true,
  }) as any;
};

export const snapM7s = async (
  server: string,
  streamPath: string,
): Promise<any> => {
  try {
    const result = await fetch(`${server}/snap/${streamPath}`);
    return await result.blob();
  } catch (e) {
    console.log('snapM7s', e);
    return null;
  }
};
